{
  "cells": [
    {
      "cell_type": "raw",
      "id": "1957f5cb",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: Supabase\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ef1f0986",
      "metadata": {},
      "source": [
        "# SupabaseVectorStore\n",
        "\n",
        "[Supabase](https://supabase.com/docs) is an open-source Firebase alternative. Supabase is built on top of PostgreSQL, which offers strong SQL querying capabilities and enables a simple interface with already-existing tools and frameworks.\n",
        "\n",
        "LangChain.js supports using a Supabase Postgres database as a vector store, using the [`pgvector`](https://github.com/pgvector/pgvector) extension. Refer to the [Supabase blog post](https://supabase.com/blog/openai-embeddings-postgres-vector) for more information.\n",
        "\n",
        "This guide provides a quick overview for getting started with Supabase [vector stores](/docs/concepts/#vectorstores). For detailed documentation of all `SupabaseVectorStore` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c824838d",
      "metadata": {},
      "source": [
        "## Overview\n",
        "\n",
        "### Integration details\n",
        "\n",
        "| Class | Package | [PY support](https://python.langchain.com/docs/integrations/vectorstores/supabase/) |  Package latest |\n",
        "| :--- | :--- | :---: | :---: |\n",
        "| [`SupabaseVectorStore`](https://api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html) | [`@langchain/community`](https://npmjs.com/@langchain/community) | ✅ |  ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "36fdc060",
      "metadata": {},
      "source": [
        "## Setup\n",
        "\n",
        "To use Supabase vector stores, you'll need to set up a Supabase database and install the `@langchain/community` integration package. You'll also need to install the official [`@supabase/supabase-js`](https://www.npmjs.com/package/@supabase/supabase-js) SDK as a peer dependency.\n",
        "\n",
        "This guide will also use [OpenAI embeddings](/docs/integrations/text_embedding/openai), which require you to install the `@langchain/openai` integration package. You can also use [other supported embeddings models](/docs/integrations/text_embedding) if you wish.\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/community @langchain/core @supabase/supabase-js @langchain/openai\n",
        "</Npm2Yarn>\n",
        "```\n",
        "\n",
        "Once you've created a database, run the following SQL to set up [`pgvector`](https://github.com/pgvector/pgvector) and create the necessary table and functions:\n",
        "\n",
        "```sql\n",
        "-- Enable the pgvector extension to work with embedding vectors\n",
        "create extension vector;\n",
        "\n",
        "-- Create a table to store your documents\n",
        "create table documents (\n",
        "  id bigserial primary key,\n",
        "  content text, -- corresponds to Document.pageContent\n",
        "  metadata jsonb, -- corresponds to Document.metadata\n",
        "  embedding vector(1536) -- 1536 works for OpenAI embeddings, change if needed\n",
        ");\n",
        "\n",
        "-- Create a function to search for documents\n",
        "create function match_documents (\n",
        "  query_embedding vector(1536),\n",
        "  match_count int DEFAULT null,\n",
        "  filter jsonb DEFAULT '{}'\n",
        ") returns table (\n",
        "  id bigint,\n",
        "  content text,\n",
        "  metadata jsonb,\n",
        "  embedding jsonb,\n",
        "  similarity float\n",
        ")\n",
        "language plpgsql\n",
        "as $$\n",
        "#variable_conflict use_column\n",
        "begin\n",
        "  return query\n",
        "  select\n",
        "    id,\n",
        "    content,\n",
        "    metadata,\n",
        "    (embedding::text)::jsonb as embedding,\n",
        "    1 - (documents.embedding <=> query_embedding) as similarity\n",
        "  from documents\n",
        "  where metadata @> filter\n",
        "  order by documents.embedding <=> query_embedding\n",
        "  limit match_count;\n",
        "end;\n",
        "$$;\n",
        "```\n",
        "\n",
        "### Credentials\n",
        "\n",
        "Once you've done this set the `SUPABASE_PRIVATE_KEY` and `SUPABASE_URL` environment variables:\n",
        "\n",
        "```typescript\n",
        "process.env.SUPABASE_PRIVATE_KEY = \"your-api-key\";\n",
        "process.env.SUPABASE_URL = \"your-supabase-db-url\";\n",
        "```\n",
        "\n",
        "If you are using OpenAI embeddings for this guide, you'll need to set your OpenAI key as well:\n",
        "\n",
        "```typescript\n",
        "process.env.OPENAI_API_KEY = \"YOUR_API_KEY\";\n",
        "```\n",
        "\n",
        "If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "```typescript\n",
        "// process.env.LANGSMITH_TRACING=\"true\"\n",
        "// process.env.LANGSMITH_API_KEY=\"your-api-key\"\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "93df377e",
      "metadata": {},
      "source": [
        "## Instantiation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "dc37144c-208d-4ab3-9f3a-0407a69fe052",
      "metadata": {
        "tags": []
      },
      "outputs": [],
      "source": [
        "import { SupabaseVectorStore } from \"@langchain/community/vectorstores/supabase\";\n",
        "import { OpenAIEmbeddings } from \"@langchain/openai\";\n",
        "\n",
        "import { createClient } from \"@supabase/supabase-js\";\n",
        "\n",
        "const embeddings = new OpenAIEmbeddings({\n",
        "  model: \"text-embedding-3-small\",\n",
        "});\n",
        "\n",
        "const supabaseClient = createClient(\n",
        "  process.env.SUPABASE_URL,\n",
        "  process.env.SUPABASE_PRIVATE_KEY\n",
        ");\n",
        "\n",
        "const vectorStore = new SupabaseVectorStore(embeddings, {\n",
        "  client: supabaseClient,\n",
        "  tableName: \"documents\",\n",
        "  queryName: \"match_documents\",\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ac6071d4",
      "metadata": {},
      "source": [
        "## Manage vector store\n",
        "\n",
        "### Add items to vector store"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "17f5efc0",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[ 1, 2, 3, 4 ]\n"
          ]
        }
      ],
      "source": [
        "import type { Document } from \"@langchain/core/documents\";\n",
        "\n",
        "const document1: Document = {\n",
        "  pageContent: \"The powerhouse of the cell is the mitochondria\",\n",
        "  metadata: { source: \"https://example.com\" }\n",
        "};\n",
        "\n",
        "const document2: Document = {\n",
        "  pageContent: \"Buildings are made out of brick\",\n",
        "  metadata: { source: \"https://example.com\" }\n",
        "};\n",
        "\n",
        "const document3: Document = {\n",
        "  pageContent: \"Mitochondria are made out of lipids\",\n",
        "  metadata: { source: \"https://example.com\" }\n",
        "};\n",
        "\n",
        "const document4: Document = {\n",
        "  pageContent: \"The 2024 Olympics are in Paris\",\n",
        "  metadata: { source: \"https://example.com\" }\n",
        "}\n",
        "\n",
        "const documents = [document1, document2, document3, document4];\n",
        "\n",
        "await vectorStore.addDocuments(documents, { ids: [\"1\", \"2\", \"3\", \"4\"] });"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dcf1b905",
      "metadata": {},
      "source": [
        "### Delete items from vector store"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "ef61e188",
      "metadata": {},
      "outputs": [],
      "source": [
        "await vectorStore.delete({ ids: [\"4\"] });"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c3620501",
      "metadata": {},
      "source": [
        "## Query vector store\n",
        "\n",
        "Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent. \n",
        "\n",
        "### Query directly\n",
        "\n",
        "Performing a simple similarity search can be done as follows:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "aa0a16fa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "* The powerhouse of the cell is the mitochondria [{\"source\":\"https://example.com\"}]\n",
            "* Mitochondria are made out of lipids [{\"source\":\"https://example.com\"}]\n"
          ]
        }
      ],
      "source": [
        "const filter = { source: \"https://example.com\" };\n",
        "\n",
        "const similaritySearchResults = await vectorStore.similaritySearch(\"biology\", 2, filter);\n",
        "\n",
        "for (const doc of similaritySearchResults) {\n",
        "  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3ed9d733",
      "metadata": {},
      "source": [
        "If you want to execute a similarity search and receive the corresponding scores you can run:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "5efd2eaa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "* [SIM=0.165] The powerhouse of the cell is the mitochondria [{\"source\":\"https://example.com\"}]\n",
            "* [SIM=0.148] Mitochondria are made out of lipids [{\"source\":\"https://example.com\"}]\n"
          ]
        }
      ],
      "source": [
        "const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore(\"biology\", 2, filter)\n",
        "\n",
        "for (const [doc, score] of similaritySearchWithScoreResults) {\n",
        "  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "180b0e66",
      "metadata": {},
      "source": [
        "### Metadata Query Builder Filtering\n",
        "\n",
        "You can also use query builder-style filtering similar to how the [Supabase JavaScript library](https://supabase.com/docs/reference/javascript/using-filters) works instead of passing an object. Note that since most of the filter properties are in the metadata column, you need to use arrow operators (-> for integer or ->> for text) as defined in [Postgrest API documentation](https://postgrest.org/en/stable/references/api/tables_views.html#json-columns) and specify the data type of the property (e.g. the column should look something like `metadata->some_int_prop_name::int`)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "e3287768",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "* The powerhouse of the cell is the mitochondria [{\"source\":\"https://example.com\"}]\n",
            "* Mitochondria are made out of lipids [{\"source\":\"https://example.com\"}]\n"
          ]
        }
      ],
      "source": [
        "import { SupabaseFilterRPCCall } from \"@langchain/community/vectorstores/supabase\";\n",
        "\n",
        "const funcFilter: SupabaseFilterRPCCall = (rpc) =>\n",
        "  rpc.filter(\"metadata->>source\", \"eq\", \"https://example.com\");\n",
        "\n",
        "const funcFilterSearchResults = await vectorStore.similaritySearch(\"biology\", 2, funcFilter);\n",
        "\n",
        "for (const doc of funcFilterSearchResults) {\n",
        "  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0c235cdc",
      "metadata": {},
      "source": [
        "### Query by turning into retriever\n",
        "\n",
        "You can also transform the vector store into a [retriever](/docs/concepts/retrievers) for easier usage in your chains. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "f3460093",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  Document {\n",
            "    pageContent: 'The powerhouse of the cell is the mitochondria',\n",
            "    metadata: { source: 'https://example.com' },\n",
            "    id: undefined\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: 'Mitochondria are made out of lipids',\n",
            "    metadata: { source: 'https://example.com' },\n",
            "    id: undefined\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const retriever = vectorStore.asRetriever({\n",
        "  // Optional filter\n",
        "  filter: filter,\n",
        "  k: 2,\n",
        "});\n",
        "await retriever.invoke(\"biology\");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e2e0a211",
      "metadata": {},
      "source": [
        "### Usage for retrieval-augmented generation\n",
        "\n",
        "For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:\n",
        "\n",
        "- [Tutorials: working with external knowledge](/docs/tutorials/#working-with-external-knowledge).\n",
        "- [How-to: Question and answer with RAG](/docs/how_to/#qa-with-rag)\n",
        "- [Retrieval conceptual docs](/docs/concepts/retrieval)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8a27244f",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all `SupabaseVectorStore` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}